package JUC;

import java.util.concurrent.atomic.AtomicReference;

public class SpinLockDemo {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() +
                "\tcome in myLock()");
        while (!atomicReference.compareAndSet(null, thread)){

        }
        System.out.println(Thread.currentThread().getName() +
                "\t修改成功");
    }

    public void myUnLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() +
                "\tcome in myUnLock()");
        atomicReference.compareAndSet(thread, null);
        System.out.println(Thread.currentThread().getName() +
                "\t释放锁成功");
    }

    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();


        new Thread(()->{spinLockDemo.myLock();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLockDemo.myUnLock();}, "AA").start();

        new Thread(()->{spinLockDemo.myLock();
            spinLockDemo.myUnLock();}, "BB").start();
    }
}
